package com.wangsd.common.component;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.wangsd.web.report.entity.ServiceBusiness;
import com.wangsd.web.report.service.ServiceBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WeixinPayService {
    @Value("${wx.pay.appId}")
    private String appId;
    @Value("${wx.pay.mchId}")
    private String mchId;
    @Value("${wx.pay.mchKey}")
    private String mchKey;
    @Value("${wx.pay.subMchId}")
    private String subMchId;

    @Autowired
    ServiceBusinessService serviceBusinessService;

    /**
     * @param env 默认为false，不使用配置文件配置的参数。true使用配置文件配置的参数
     * @return
     */
    public WxPayService getService(boolean env) {
        if (!env) { //不使用配置文件配置的参数
            appId = null;
            mchId = null;
            mchKey = null;
            subMchId = null;
        }
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        payConfig.setMchId(mchId);
        payConfig.setMchKey(mchKey);
        payConfig.setSubMchId(subMchId);

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }


    public WxPayService getService(Long businessId, String subMchId) {
        //不使用配置文件配置的参数
        if (businessId != null) {
            ServiceBusiness business = serviceBusinessService.getById(businessId);
            mchId = business.getWxMchId();
            mchKey = business.getWxMchKey();
            appId = business.getWxAppId();
        }
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        payConfig.setMchId(mchId);
        payConfig.setMchKey(mchKey);
        if (subMchId != null) {
            payConfig.setSubMchId(subMchId);
        }

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}
